import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiResponse } from '../constants/api-response.constant';
import { ResponseUtil } from '../utils/response.util';
import { Response } from 'express';

@Injectable()
export class ApiResponseInterceptor<T>
  implements NestInterceptor<T, ApiResponse<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<ApiResponse<T>> {
    const response = context.switchToHttp().getResponse<Response>();
    response.status(200); // 设置全局接口响应HTTP状态码为 200
    return next.handle().pipe(map((data) => ResponseUtil.ok(data)));
  }
}
